package com.rpc.center.discover.client.manager;

import com.rpc.common.entity.HostInfoPair;
import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Getter
@Setter
@Service
public class ServerAddressManager {
    private Map<String, Integer> serverAddress2Port;  //保存服务端地址和端口号

    private static class ManageHolder {
        public static ServerAddressManager configure = new ServerAddressManager();
    }

    /**
     * 私有构造
     */
    private ServerAddressManager() {
        //使用ConcurrentHashMap防止多线程并发异常
        serverAddress2Port = new ConcurrentHashMap<>();
        //mockInitAddress();
    }

    private void mockInitAddress() {
        serverAddress2Port.put("127.0.0.1", 8000);
    }

    public static ServerAddressManager getAddressManagerInstance() {
        return ManageHolder.configure;
    }

    //返回可用的服务方地址，todo 目前就返回第一个地址  后续可能需要负载均衡策略
    public Map.Entry<String, Integer> getAvailableServer() {
        for (Map.Entry<String, Integer> entry : serverAddress2Port.entrySet()) {
            return entry;
        }
        return null;    //可用地址为空的时候返回null
    }

    /**
     * 批量添加服务器可用地址，一般服务发现后会调用
     *
     * @param addressList
     */
    public void addAvaliableServerList(List<HostInfoPair> addressList) {
        if (addressList == null || addressList.isEmpty()) {
            return;
        }
        for (HostInfoPair pair : addressList) {
            serverAddress2Port.put(pair.getAddress(), pair.getPort());
        }
    }

    /**
     * 新增可用服务器地址
     *
     * @param hostAddress
     * @param port
     */
    public void addAvaliableServer(String hostAddress, int port) {
        serverAddress2Port.put(hostAddress, port);
    }

    public void removePublisher(String address){
        serverAddress2Port.remove(address);
    }
}
